﻿using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Shapes;
using ZhuXingFamilys.CADInformation.Entity;
using Line = Autodesk.Revit.DB.Line;


namespace ZhuXingFamilys.CADInformation.Utils
{
    [Transaction(TransactionMode.Manual)]
    public class ReadCad : IExternalEventHandler
    {
        public ExternalEvent ExEvent { get; set; }

        Application app;
        Document doc;
        // 分类
        public string classification = string.Empty;
        // 线层
        public List<SelectedLayers> lineCategories = new List<SelectedLayers>();
        // 符层
        public List<SelectedLayers> symbolCategories = new List<SelectedLayers>();
        public void Execute(UIApplication uiApp)
        {
            UIDocument uidoc = uiApp.ActiveUIDocument;
            app = uiApp.Application;
            doc = uiApp.ActiveUIDocument.Document;

            Reference r = lineCategories[0].selectedReference;
            Element elem = doc.GetElement(r);
            GeometryElement geoElem = elem.get_Geometry(new Options());
            GeometryObject geoObj = elem.GetGeometryObjectFromReference(r);
            ElementId graphicsStyleId = geoObj.GraphicsStyleId;

            // 选中的cad图层
            Category targetCategory = lineCategories[0].selectedCategory;

            // 隐藏选中的cad图层
            Transaction trans = new Transaction(doc, "隐藏图层");
            trans.Start();
            if (targetCategory != null)
                targetCategory.set_Visible(doc.ActiveView,false);
                //doc.ActiveView.SetVisibility(targetCategory, false);
            trans.Commit();

            if (classification == "轴网")
            {
                // 获取轴网图层
                Category axisGridCategory = lineCategories.FirstOrDefault(c => c.Name == "轴网")?.selectedCategory;

                if (axisGridCategory != null)
                {
                    // 显示轴网图层
                    Transaction showTrans = new Transaction(doc, "显示轴网图层");
                    showTrans.Start();
                    axisGridCategory.set_Visible(doc.ActiveView, true);
                    showTrans.Commit();

                    // 创建轴网
                    Transaction createAxisTrans = new Transaction(doc, "创建轴网");
                    createAxisTrans.Start();

                    // 根据需求创建轴网，此处仅示例创建一条简单的直线轴网
                    XYZ startPoint = new XYZ(0, 0, 0);
                    XYZ endPoint = new XYZ(10, 10, 0);
                    Line axisLine = Line.CreateBound(startPoint, endPoint);

                    doc.Create.NewDetailCurve(doc.ActiveView, axisLine);

                    createAxisTrans.Commit();

                    // 隐藏轴网图层
                    Transaction hideTrans = new Transaction(doc, "隐藏轴网图层");
                    hideTrans.Start();
                    axisGridCategory.set_Visible(doc.ActiveView, false);
                    hideTrans.Commit();
                }
            }

            TransactionGroup transGroup = new TransactionGroup(doc, "绘制模型线");
            transGroup.Start();
            CurveArray curveArray = new CurveArray();


            //判断元素类型
            foreach (var gObj in geoElem)
            {
                GeometryInstance geomInstance = gObj as GeometryInstance;
                //坐标转换。如果选择的是“自动-中心到中心”，或者移动了importInstance，需要进行坐标转换
                Transform transform = geomInstance.Transform;


                if (null != geomInstance)
                {
                    foreach (var insObj in geomInstance.SymbolGeometry)
                    {
                        if (insObj.GraphicsStyleId.IntegerValue != graphicsStyleId.IntegerValue)
                            continue;


                        if (insObj.GetType().ToString() == "Autodesk.Revit.DB.NurbSpline")
                        {
                            //未实现
                        }
                        if (insObj.GetType().ToString() == "Autodesk.Revit.DB.Line")
                        {
                            Line line = insObj as Line;
                            XYZ normal = XYZ.BasisZ;
                            XYZ point = line.GetEndPoint(0);
                            point = transform.OfPoint(point);


                            curveArray.Append(TransformLine(transform, line));


                            CreateModelCurveArray(curveArray, normal, point);
                        }
                        if (insObj.GetType().ToString() == "Autodesk.Revit.DB.Arc")
                        {
                            //未实现
                        }
                        if (insObj.GetType().ToString() == "Autodesk.Revit.DB.PolyLine")
                        {
                            PolyLine polyLine = insObj as PolyLine;
                            IList<XYZ> points = polyLine.GetCoordinates();


                            for (int i = 0; i < points.Count - 1; i++)
                            {
                                Line line = Line.CreateBound(points[i], points[i + 1]);
                                line = TransformLine(transform, line);
                                curveArray.Append(line);
                            }


                            XYZ normal = XYZ.BasisZ;
                            XYZ point = points.First();
                            point = transform.OfPoint(point);


                            CreateModelCurveArray(curveArray, normal, point);
                        }
                    }
                }
            }
            transGroup.Assimilate();

        }
        private void CreateModelCurveArray(CurveArray curveArray, XYZ normal, XYZ point)
        {
            if (curveArray.Size > 0)
            {
                Transaction transaction2 = new Transaction(doc);
                transaction2.Start("绘制模型线");
                try
                {
                    Plane plane = Plane.CreateByNormalAndOrigin(normal, point);
                    SketchPlane modelSketch = SketchPlane.Create(doc, plane);
                    ModelCurveArray modelLine = doc.Create.NewModelCurveArray(curveArray, modelSketch);

                }
                catch
                {


                }
                transaction2.Commit();
                curveArray.Clear();
            }
        }


        private Line TransformLine(Transform transform, Line line)
        {
            XYZ startPoint = transform.OfPoint(line.GetEndPoint(0));
            XYZ endPoint = transform.OfPoint(line.GetEndPoint(1));
            Line newLine = Line.CreateBound(startPoint, endPoint);
            return newLine;
        }

        public string GetName()
        {
            return "ReadCad";
        }
    }
}
